use nokhwa::utils::CameraIndex;
use nokhwa::utils::RequestedFormat;
use nokhwa::pixel_format::RgbFormat;
use nokhwa::utils::RequestedFormatType;
use nokhwa::{Camera, NokhwaError};

use std::io::Cursor;

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
fn picture(name: &str) -> Vec<u8>{
    // first camera in system
    let index = CameraIndex::Index(0);
    // request the absolute highest resolution CameraFormat that can be decoded to RGB.
    let requested = RequestedFormat::new::<nokhwa::pixel_format::RgbFormat>(RequestedFormatType::None);
    // make the camera
    let mut camera = Camera::new(index, requested).unwrap();

    //camera info
    let camera_info = camera.info();
    println!("camera info {:?}", camera_info);

    let frame_rate = camera.frame_rate();
    println!("frame rate {}", frame_rate);

    let is_open_camera = camera.is_stream_open();
    println!("camera is open: {}", is_open_camera);

    let err = camera.open_stream();
    eprintln!("error : {:?}", err);

    // get a frame
    // Capture a frame
    let frame = camera.frame().unwrap();
    println!("Captured Single Frame of {}", frame.buffer().len());
    // decode into an ImageBuffer
    let decoded = frame.decode_image::<RgbFormat>().unwrap();
    println!("Decoded Frame of {}", &decoded.len());
   // println!("decoded info {:?}", &decoded);

    let path = format!("/home/owen/code/rust_project/{}.jpeg",name);
    let _ = &decoded.save(&path);//必须指定名称，后缀名
    let _ = camera.stop_stream();
    //let image_raw_buffer = &decoded.into_raw();
   // println!("{:?}", image_raw_buffer);
    //image_raw_buffer
    //decoded.into_vec()

    let mut bytes = Vec::new();
    let mut cursor = Cursor::new(&mut bytes);
    decoded.write_to(&mut cursor, image::ImageFormat::Png)
        .expect("Failed to encode image");
    bytes
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![greet,picture])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
